<?php
/**
 * Created by PhpStorm.
 * User: zhaoye
 * Date: 2016/10/24
 * Time: 下午4:33
 */

namespace model;
use ZPHP\Core\Db;
use tool\Validation;
use ZPHP\Core\Log;
use tool\Easemob;

class Member extends Base{

    /**
     * 数据验证
     * @param $params
     * @return bool
     */
    public function username_v($username)
    {
        $validation = new Validation();
        if($validation->isEmpty($username) === false)
        {
            $this->code = 1002;
            $this->msg = '用户名为空';
            return false;
        }
        return true;
    }
    public function password_v($password)
    {
        $validation = new Validation();
        if($validation->isEmpty($password) === false)
        {
            $this->code = 1004;
            $this->msg = '密码为空';
            return false;
        }
        return true;
    }

    public function nickname_v($nickname)
    {
        $validation = new Validation();
        if($validation->isEmpty($nickname) === false)
        {
            $this->code = 1008;
            $this->msg = '昵称不能为空';
            return false;
        }
        return true;
    }

    /**
     * 判断用户是否存在
     * @param $username
     * @return bool
     */

    public function isExistsUser($username)
    {
        if($this->username_v($username) === false)
        {
            //未通过验证
            return false;
        }
        $res1 = yield Db::collection('lqhn_members')->where(['username'=>$username])->count();
        if(!$res1)
        {
            $this->code = 1006;
            $this->msg = '用户['.$username.']不存在';
            return false;
        }
        return true;
    }


    /**
     * 注册
     * @param $request
     * @return bool
     */
    public function login($params)
    {
        $username = $params['username'];
        $password = $params['password'];
        if($this->username_v($username) === false || $this->password_v($password) === false)
        {
            //未通过验证
            return false;
        }
        $password = md5($params['password']);

        $res = yield Db::collection('lqhn_members')->where(['username'=>$username])->find();
        if(!is_array($res))
        {
            $this->code = 1006;
            $this->msg = '用户'.$username.'不存在';
            return false;
        }
        if($res['password'] != $password)
        {
            $this->code = 1010;
            $this->msg = '密码不正确';
            return false;
        }
        //token
//        $token = 'zsq_'.$res['_id'];
//        yield Db::redis()->cache($token,$username,60*60);
        return true;

    }


    /**
     * 注册
     * @param $request
     * @return bool
     */
    public function reg($params)
    {
        $username = $params['username'];
        $password = $params['password'];
        if($this->username_v($username) === false || $this->password_v($password) === false)
        {
            //未通过验证
            return false;
        }
        $password = md5($params['password']);
        $nickname = isset($params['nickname'])?$params['nickname']:'';

        $res = yield Db::collection('lqhn_members')->where(['username'=>$username])->count();
        if($res)
        {
            $this->code = 1001;
            $this->msg = '用户'.$username.'已存在';
            return false;
        }
//        $time = str_replace('.','',microtime(true));
        $time = getMillisecond();
        $res2 = yield Db::collection('lqhn_members')->add(['username'=>$username,'password'=>$password,'nickname'=>$nickname,'ico'=>'','isonline'=>'offline','type'=>'user','friendlist'=>[],'blacklist'=>[],'groupids'=>[],'roomids'=>[],'created'=>$time,'modified'=>$time,'activated'=>true]);
        if(!$res2)
        {
            $this->code = 101;
            $this->msg = '新增用户'.$username.'失败';
            return false;
        }
        return '';

    }


    /**
     * 批量注册
     * @param $request
     * @return bool
     */
    public function regs($params)
    {
        $error = [];
        foreach($params as $v)
        {
            $_res = yield $this->reg($v);
            if($_res === false)
            {
                $error[$v['username']] = ['code'=>$this->code,'msg'=>$this->msg];
            }
        }
        if(count($error))
        {
            $this->code = 102;
            $this->msg = '部分数据新增失败,查看errordata详情';
            return $error;
        }
        return true;
    }

    /**
     * 重置密码
     * @return bool
     */
    public function resetPassword($params)
    {
        $username = $params['username'];
        $password = $params['newpassword'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        if($this->password_v($password) === false)
        {
            return false;
        }
        $password = md5($params['newpassword']);
//        $time = str_replace('.','',microtime(true));
        $time = getMillisecond();
        $res2 = yield Db::collection('lqhn_members')->where(['username'=>$username])->save(['password'=>$password,'modified'=>$time]);
        if(!$res2)
        {
            $this->code = 1007;
            $this->msg = '用户['.$username.']重置密码失败';
            return false;
        }
        return true;

    }

    /**
     * 获取用户
     * @return bool
     */
    public function getUser($params)
    {
        $username = $params['username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $data = yield Db::collection('lqhn_members')->where(['username'=>$username])->field('_id,username,nickname,type,created,modified,activated')->find();
        return $data;

    }
    /**
     * 获取用户
     * @return bool
     */
    public function getUsers($params)
    {
        $page = isset($params['page'])?$params['page']:1;
        $num = isset($params['num'])?$params['num']:10;
        //计算总页数
        $count = yield Db::collection('lqhn_members')->count();
        $data['totalPage'] = $totalPage = ceil($count/$num) <= 0?1:ceil($count/$num);
        //计算要获取第几页数据
        $page = $page >1 ? $page : 1;
        $currentPage = $totalPage > $page ? $page : $totalPage;
        $skip = ($currentPage-1)*$num;
        $data['currentPage'] = $currentPage;
        $data['list'] = yield Db::collection('lqhn_members')->field('_id,username,nickname,type,created,modified,activated')->limit($num,$skip)->get();
        return $data;

    }

    /**
     * 删除用户
     * @return bool
     */
    public function deleteUser($params)
    {
        $username = $params['username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $res2 = yield Db::collection('lqhn_members')->where(['username'=>$username])->delete();
        if(!$res2)
        {
            $this->code = 105;
            $this->msg = '删除用户['.$username.']失败';
            return false;
        }
        return true;
    }

    /**
     * 删除用户
     * @return bool
     */
    public function deleteUsers($params)
    {
        $error = [];
        $usernames = $params['usernames'];
        foreach($usernames as $v)
        {
            $_res = yield $this->deleteUser(['username'=>$v]);
            if($_res === false)
            {
                $error[$v] = ['code'=>$this->code,'msg'=>$this->msg];
            }
        }
        if(count($error))
        {
            $this->code = 102;
            $this->msg = '部分数据删除失败，查看errordata详情';
            return $error;
        }
        return true;
    }

    /**
     * 删除用户
     * @return bool
     */
    public function editNickname($params)
    {
        $username = $params['username'];
        $nickname = $params['nickname'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        if($this->nickname_v($nickname) === false)
        {
            //未通过验证
            return false;
        }
//        $time = str_replace('.','',microtime(true));
        $time = getMillisecond();
        $res2 = yield Db::collection('lqhn_members')->where(['username'=>$username])->save(['nickname'=>$nickname,'modified'=>$time]);
        if(!$res2)
        {
            $this->code = 1009;
            $this->msg = '用户['.$username.']修改昵称失败';
            return false;
        }
        return true;

    }

    /**
     * 添加好友
     * @return bool
     */
    public function addFriend($params)
    {

        $username = $params['owner_username'];
        $friendname = $params['friend_username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $res = yield $this->isExistsUser($friendname);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $res2 = yield Db::collection('lqhn_members')->where(['username'=>$username])->addToSet(['friendlist'=>$friendname]);
        if(!$res2)
        {
            $this->code = 2001;
            $this->msg = '已经添加['.$friendname.']为好友';
            return false;
        }
        $res3 = yield Db::collection('lqhn_members')->where(['username'=>$friendname])->addToSet(['friendlist'=>$username]);
        if(!$res3)
        {
            $this->code = 2001;
            $this->msg = '已经添加['.$username.']为好友';
            return false;
        }
        return true;

    }

    /**
     * 删除好友
     * @return bool
     */
    public function deleteFriend($params)
    {
        $username = $params['owner_username'];
        $friendname = $params['friend_username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $res = yield $this->isExistsUser($friendname);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $res2 = yield Db::collection('lqhn_members')->where(['username'=>$username])->pull(['friendlist'=>$friendname]);
        if(!$res2)
        {
            $this->code = 2002;
            $this->msg = '无法删除,['.$friendname.']已经不是你的好友';
            return false;
        }
        return true;

    }

    /**
     * 查看好友
     * @return bool
     */
    public function showFriends($params)
    {
        $username = $params['owner_username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $res2 = yield Db::collection('lqhn_members')->where(['username'=>$username])->field('friendlist')->find();
        $data['friendlist'] = $res2['friendlist'];
        $data['count'] = count($res2['friendlist']);
        return $data;

    }

    /**
     * 查看好友
     * @return bool
     */
    public function getBlacklist($params)
    {
        $username = $params['owner_username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $res2 = yield Db::collection('lqhn_members')->where(['username'=>$username])->field('blacklist')->find();
        $data['blacklist'] = $res2['blacklist'];
        $data['count'] = count($res2['blacklist']);
        return $data;

    }

    /**
     * 往黑名单中加人
     * @return bool
     */
    public function addUserForBlacklist($params)
    {
        $username = $params['owner_username'];
        $usernames = isset($params['usernames'])?$params['usernames']:[];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        foreach($usernames as $v)
        {
            $res = yield $this->isExistsUser($v);
            if($res === false)
            {
                //未通过验证
                return false;
            }
        }
        foreach($usernames as $v)
        {
            yield Db::collection('lqhn_members')->where(['username'=>$username])->addToSet(['blacklist'=>$v]);
        }
        $res2 = yield Db::collection('lqhn_members')->where(['username'=>$username])->field('blacklist')->find();
        $data['blacklist'] = $res2['blacklist'];
        $data['count'] = count($res2['blacklist']);
        return $data;

    }

    /**
     * 从黑名单中减人
     * @return bool
     */
    public function deleteUserFromBlacklist($params)
    {
        $username = $params['owner_username'];
        $blocked_username = $params['blocked_username'];

        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $res = yield $this->isExistsUser($blocked_username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $res2 = yield Db::collection('lqhn_members')->where(['username'=>$username])->pull(['blacklist'=>$blocked_username]);
        if(!$res2)
        {
            $this->code = 2003;
            $this->msg = '用户['.$blocked_username.']不在你的黑名单中';
            return false;
        }
        $data = yield $this->getUser(['username'=>$blocked_username]);
        return $data;

    }

    /**
     * 查看用户是否在线
     * @return bool
     */
    public function isOnline($params)
    {
        $username = $params['username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $data = yield Db::collection('lqhn_members')->where(['username'=>$username])->field('isonline')->find();
        return $data;

    }


    /**
     * 查看用户离线消息数
     * @return bool
     */
    public function getOfflineMessages($params)
    {
        $username = $params['username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        return '';

    }

    /**
     * 禁用用户账号
     * @return bool
     */
    public function deactiveUser($params)
    {
        $username = $params['username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
//        $time = str_replace('.','',microtime(true));
        $time = getMillisecond();
        yield Db::collection('lqhn_members')->where(['username'=>$username])->save(['activated'=>false,'modified'=>$time]);
        $data = yield $this->getUser(['username'=>$username]);
        return $data;

    }

    /**
     * 解禁用户账号
     * @return bool
     */
    public function activeUser($params)
    {
        $username = $params['username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }
        $time = getMillisecond();
        yield Db::collection('lqhn_members')->where(['username'=>$username])->save(['activated'=>true,'modified'=>$time]);
        $data = yield $this->getUser(['username'=>$username]);
        return $data;

    }

    /**
     * 强制用户下线
     * @return bool
     */
    public function disconnectUser($params)
    {
        $username = $params['username'];
        $res = yield $this->isExistsUser($username);
        if($res === false)
        {
            //未通过验证
            return false;
        }

        return '';

    }




}